package com.shuimin.service;

import com.shuimin.service.model.sys.Rank;
import com.shuimin.service.service.sys.RankService;
import pond.db.Record;
import pond.web.EndToEndException;
import pond.web.Render;
import pond.web.Router;

/**
 * Created by ed on 1/20/16.
 */
public class RANK extends Router {
  {
    get("/", (req, resp) -> {
      resp.render(Render.json(RankService.all()));
    });

    get("/:id", (req, resp) -> {
      resp.render(Render.json(RankService.get(req.paramNonBlank("id", "id 不能为空"))));
    });

//    put("/:id/:type", (req, resp) -> {
//      Integer type = Convert.toInt(req.paramNonBlank("type"));
//      if(type == null) throw new RuntimeException("invalid type");
//      App.DB.post(t -> {
//        t.exec(RankService.setRankType(req.paramNonBlank("id"),type));
//      });
//      resp.send(204);
//    });

    post("/", (req, resp) -> {
      req.paramNonBlank("name", "name 不能为空");
      Rank r = (Rank) Record.newEntity(Rank.class).merge(req.toMap());

      App.DB.post(t -> {
        RankService.add(t, r);
      });

      resp.status(201);
      resp.render(Render.json(r));
    });

    del("/:id", (req, resp) -> {
      String id = req.paramNonBlank("id", "id 不能为空");

      App.DB.post(t -> {
        RankService.del(t, id);
      });

      resp.send(204, id);
    });

    put("/:id", (req, resp) -> {
      String id = req.paramNonBlank("id", "id 不能为空");
      Rank cur = RankService.get(id);
      if (cur == null) {
        throw new EndToEndException(404, "岗位" + id + "没找到");
      }
//      cur.set("name", req.param("name")).set("remark", req.param("remark"));
      cur.merge(req.toMap());

      App.DB.post(t -> {
        RankService.update(t, cur);
      });

      resp.send(204, id);
    });

    get("/:id/roles/", (req, resp) -> {
      resp.render(Render.json(App.DB.get(t -> RankService.rolesForRank(t, req.paramNonBlank("id", "id不能为空")))));
    });

    post("/:rank_id/roles/:role_id", (req, resp) -> {
      App.DB.post(t -> RankService.addRoleToRank(t, req.paramNonBlank("role_id"), req.paramNonBlank("rank_id")));
      resp.send(201);
    });

    del("/:rank_id/roles/:role_id", (req, resp) -> {
      App.DB.post(t -> RankService.removeRoleFromRank(t, req.paramNonBlank("role_id"), req.paramNonBlank("rank_id")));
      resp.send(204);
    });
  }
}
